package com.css.bjdt_report.report.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.css.bjdt_report.dataSetManage.entity.DataItem;
import com.css.bjdt_report.dataSetManage.entity.DataSet;
import com.css.bjdt_report.dataSetManage.service.DataItemService;
import com.css.bjdt_report.dataSetManage.service.DataSetService;
import com.css.bjdt_report.report.entity.RptTemplateCondition;
import com.css.bjdt_report.report.entity.RptTemplateCondition.ConditionType;
import com.css.bjdt_report.report.entity.RptTemplateStatCategory;
import com.css.bjdt_report.report.entity.ViewRptTemplateCondition;
import com.css.bjdt_report.report.service.ReportConditionService;
import com.css.bjdt_report.report.service.ReportStatCategoryService;
import com.css.bjdt_report.util.CommonUtil;
import com.css.bjdt_report.util.JsonResult;
import com.css.bjdt_report.util.PropertyFilter;

//行列条件处理层
@Controller
@RequestMapping(value = "/reportTemplateConditionsController")
public class ReportTemplateConditionsController {

	@Autowired
	private ReportConditionService reportConditionService;

	@Autowired
	private DataSetService dataSetService;

	@Autowired
	private DataItemService dataItemService;

	@Autowired
	private ReportStatCategoryService reportStatCategoryService;

	//得到数据集（就是所有表名）
	@ResponseBody
	@RequestMapping(value = "/getAllDataSet")
	public List<DataSet> getAllDataSet() {
		List<DataSet> dataSetList = dataSetService.query(null);
		return dataSetList;
	}

	@ResponseBody
	@RequestMapping(value = "/getAllDataItemBySetId/{dataSetId}")
	public List<DataItem> getAllDataItemBySetId(@PathVariable String dataSetId) {
		List<DataItem> dataItemList = dataItemService.query(Cnd.where("SETID", "=", dataSetId));
		return dataItemList;
	}

	@Transactional
	@ResponseBody
	@RequestMapping(value = "/saveConditions/{templateId}", method = RequestMethod.POST)
	public void saveConditions(@PathVariable String templateId,
			@RequestParam(value = "zongkongText") String zongkongText,
			@RequestParam(value = "hangText") String hangText, @RequestParam(value = "lieText") String lieText,
			@RequestParam(value = "dataSetSelectId") String dataSetSelectId,
			@RequestParam(value = "dataItemSelectId") String dataItemSelectId,
			@RequestParam(value = "itemStatTimeSelectId") String itemStatTimeSelectId,
			@RequestParam(value = "itemUnitIdSelectId") String itemUnitIdSelectId, Model model) {
		List<RptTemplateCondition> rptTemplateConditionListZongkong = zongkongJson(zongkongText, templateId);
		List<RptTemplateCondition> rptTemplateConditionListHang = hangJson(hangText, templateId);
		List<RptTemplateCondition> rptTemplateConditionListLie = lieJson(lieText, templateId);
		//删除该报表的总控、行、列条件
		reportConditionService.deleteTotalRowCol(templateId);
		//保存总控条件
		reportConditionService.insertList(rptTemplateConditionListZongkong);
		//保存行条件
		reportConditionService.insertList(rptTemplateConditionListHang);
		//保存列条件
		reportConditionService.insertList(rptTemplateConditionListLie);
		//保存统计信息集
		RptTemplateStatCategory rptTemplateStatCategory = new RptTemplateStatCategory();
		rptTemplateStatCategory.setSetId(dataSetSelectId);
		rptTemplateStatCategory.setItemId(dataItemSelectId);
		rptTemplateStatCategory.setTemplateId(templateId);
		rptTemplateStatCategory.setItemStatTimeId(itemStatTimeSelectId);
		rptTemplateStatCategory.setItemUnitId(itemUnitIdSelectId);
		reportStatCategoryService.insert(rptTemplateStatCategory);
	}

	//总控条件的JSON解析(将总控条件的JSON转换成LIST)
	public List<RptTemplateCondition> zongkongJson(String zongkongText, String templateId) {
		try {
			List<RptTemplateCondition> rptTemplateConditionList = new ArrayList<RptTemplateCondition>();
			JsonResult jsonResult = new JsonResult();
			Map<String, String> map = jsonResult.jsonToString(zongkongText);
			Set<String> key = map.keySet();
			for (String strKey : key) {
				String strJson = "{" + map.get(strKey) + "}";
				JSONObject jobj = new JSONObject(strJson);
				RptTemplateCondition rptTemplateCondition = new RptTemplateCondition();
				rptTemplateCondition.setSetId(jobj.getString("xinxijiId"));
				rptTemplateCondition.setItemId(jobj.getString("xinxixiangId"));
				rptTemplateCondition.setConditionVal(jobj.getString("zongkongZhi"));
				//这一定要注意，不是写错了，是前台写错了，不好改
				//逻辑运算服和关系运算服互相调换下位置，因为改页面太麻烦了，故在塞值的时候将其调换位置
				//逻辑连接符塞值
				rptTemplateCondition.setLogicOperator(jobj.getString("lianjieId"));
				//关系预算符塞值
				rptTemplateCondition.setRelaOperator(jobj.getString("luojiyusuanfuId"));
				rptTemplateCondition.setConditionType(ConditionType.total.getKey());
				rptTemplateCondition.setComboType(jobj.getString("shifouyouxianId"));
				rptTemplateCondition.setTemplateId(templateId);
				rptTemplateCondition.setOrderId(Integer.parseInt(jobj.getString("orderId")));
				rptTemplateConditionList.add(rptTemplateCondition);
			}
			return rptTemplateConditionList;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	//行条件的JSON解析(将行条件的JSON转换成LIST)
	public List<RptTemplateCondition> hangJson(String hangText, String templateId) {
		try {
			List<RptTemplateCondition> rptTemplateConditionList = new ArrayList<RptTemplateCondition>();
			JsonResult jsonResult = new JsonResult();
			Map<String, String> map = jsonResult.jsonToString(hangText);
			Set<String> key = map.keySet();
			for (String strKey : key) {
				String strJson = "{" + map.get(strKey) + "}";
				JSONObject jobj = new JSONObject(strJson);
				RptTemplateCondition rptTemplateCondition = new RptTemplateCondition();
				rptTemplateCondition.setSetId(jobj.getString("hXinxijiId"));
				rptTemplateCondition.setItemId(jobj.getString("hXinxixiangId"));
				rptTemplateCondition.setConditionVal(jobj.getString("hangZhi"));
				//这一定要注意，不是写错了，是前台写错了，不好改
				//逻辑运算服和关系运算服互相调换下位置，因为改页面太麻烦了，故在塞值的时候将其调换位置
				//逻辑连接符塞值
				rptTemplateCondition.setLogicOperator(jobj.getString("hLianjieId"));
				//关系预算符塞值
				rptTemplateCondition.setRelaOperator(jobj.getString("hLuojiyusuanfuId"));
				rptTemplateCondition.setConditionType(ConditionType.row.getKey());
				rptTemplateCondition.setComboType(jobj.getString("hShifouyouxianId"));
				rptTemplateCondition.setRelRowNum(jobj.getString("hangNum"));
				rptTemplateCondition.setTemplateId(templateId);
				rptTemplateCondition.setOrderId(Integer.parseInt(jobj.getString("orderId")));
				rptTemplateConditionList.add(rptTemplateCondition);
			}
			return rptTemplateConditionList;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	//列条件的JSON解析(将列条件的JSON转换成LIST)
	public List<RptTemplateCondition> lieJson(String lieText, String templateId) {
		try {
			List<RptTemplateCondition> rptTemplateConditionList = new ArrayList<RptTemplateCondition>();
			JsonResult jsonResult = new JsonResult();
			Map<String, String> map = jsonResult.jsonToString(lieText);
			Set<String> key = map.keySet();
			for (String strKey : key) {
				String strJson = "{" + map.get(strKey) + "}";
				JSONObject jobj = new JSONObject(strJson);
				RptTemplateCondition rptTemplateCondition = new RptTemplateCondition();
				rptTemplateCondition.setSetId(jobj.getString("lXinxijiId"));
				rptTemplateCondition.setItemId(jobj.getString("lXinxixiangId"));
				rptTemplateCondition.setConditionVal(jobj.getString("lieZhi"));
				//这一定要注意，不是写错了，是前台写错了，不好改
				//逻辑运算服和关系运算服互相调换下位置，因为改页面太麻烦了，故在塞值的时候将其调换位置
				//逻辑连接符塞值
				rptTemplateCondition.setLogicOperator(jobj.getString("lLianjieId"));
				//关系预算符塞值
				rptTemplateCondition.setRelaOperator(jobj.getString("lLuojiyusuanfuId"));
				rptTemplateCondition.setConditionType(ConditionType.col.getKey());
				rptTemplateCondition.setComboType(jobj.getString("lShifouyouxianId"));
				rptTemplateCondition.setRelColNum(jobj.getString("lieNumId"));
				rptTemplateCondition.setTemplateId(templateId);
				rptTemplateCondition.setOrderId(Integer.parseInt(jobj.getString("orderId")));
				rptTemplateConditionList.add(rptTemplateCondition);
			}
			return rptTemplateConditionList;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	//通过报表的ID，获取总控条件
	@ResponseBody
	@RequestMapping(value = "/getZongkongCondByTemplateId/{templateId}")
	public Map getZongkongCondByTemplateId(@PathVariable String templateId, HttpServletRequest request,
			@RequestParam(value = "pageNum") int pageNum, @RequestParam(value = "pageSize") int pageSize,
			@RequestParam(value = "sortname") String sortname, @RequestParam(value = "sortorder") String sortorder) {
		Criteria cnd = PropertyFilter.cri(request);
		cnd.where().and("TEMPLATE_ID", "=", templateId).and("CONDITION_TYPE", "=", ConditionType.total.getKey());
		cnd.getOrderBy().asc("ORDER_ID");

		return reportConditionService.getConditionByTypeLigerUi(cnd, pageNum, pageSize);
	}

	//通过报表的ID，获取行条件
	@ResponseBody
	@RequestMapping(value = "/getHangCondByTemplateId/{templateId}")
	public Map getHangCondByTemplateId(@PathVariable String templateId, HttpServletRequest request,
			@RequestParam(value = "pageNum") int pageNum, @RequestParam(value = "pageSize") int pageSize,
			@RequestParam(value = "sortname") String sortname, @RequestParam(value = "sortorder") String sortorder) {
		Criteria cnd = PropertyFilter.cri(request);
		cnd.where().and("TEMPLATE_ID", "=", templateId).and("CONDITION_TYPE", "=", ConditionType.row.getKey());
		cnd.getOrderBy().asc("ORDER_ID");

		return reportConditionService.getConditionByTypeLigerUi(cnd, pageNum, pageSize);
	}

	//通过报表的ID，获取列条件
	@ResponseBody
	@RequestMapping(value = "/getLieCondByTemplateId/{templateId}")
	public Map getLieCondByTemplateId(@PathVariable String templateId, HttpServletRequest request,
			@RequestParam(value = "pageNum") int pageNum, @RequestParam(value = "pageSize") int pageSize,
			@RequestParam(value = "sortname") String sortname, @RequestParam(value = "sortorder") String sortorder) {
		Criteria cnd = PropertyFilter.cri(request);
		cnd.where().and("TEMPLATE_ID", "=", templateId).and("CONDITION_TYPE", "=", ConditionType.col.getKey());
		cnd.getOrderBy().asc("ORDER_ID");

		Map resultMap = reportConditionService.getConditionByTypeLigerUi(cnd, pageNum, pageSize);
		Map resultNewMap = new HashMap();
		List<RptTemplateCondition> rptTemplateConditionList = (List<RptTemplateCondition>) resultMap.get("Rows");
		List<RptTemplateCondition> rptTemplateConditionNewList = new ArrayList<RptTemplateCondition>();
		for (RptTemplateCondition rptTemplateCondition : rptTemplateConditionList) {
			rptTemplateCondition.setColLetter(CommonUtil.numToLetter(rptTemplateCondition.getRelColNum()));
			rptTemplateConditionNewList.add(rptTemplateCondition);
		}
		resultNewMap.put("Rows", rptTemplateConditionNewList);
		return resultNewMap;
	}

	//通过报表的ID，获取单元格条件
	@ResponseBody
	@RequestMapping(value = "/getCellCondByTemplateId/{templateId}/{row}/{col}")
	public List<ViewRptTemplateCondition> getCellCondByTemplateId(@PathVariable String templateId,
			@PathVariable String row, @PathVariable String col) {
		List<ViewRptTemplateCondition> rptTemplateConditionList = reportConditionService
				.getCellConditionByType(templateId, ConditionType.cell, row, col);
		List<ViewRptTemplateCondition> rptTemplateConditionListNew = new ArrayList<ViewRptTemplateCondition>();
		for (ViewRptTemplateCondition viewRptTemplateCondition : rptTemplateConditionList) {
			viewRptTemplateCondition
					.setJspRelaOperatorShow(getRelaOperatorName(viewRptTemplateCondition.getRelaOperator()));
			viewRptTemplateCondition.setJspComboTypeShow(getComboTypeName(viewRptTemplateCondition.getComboType()));
			viewRptTemplateCondition
					.setJspLogicOperatorShow(getLogicOperatorName(viewRptTemplateCondition.getLogicOperator()));
			rptTemplateConditionListNew.add(viewRptTemplateCondition);
		}
		return rptTemplateConditionListNew;
	}

	//保存单元格的条件
	@ResponseBody
	@RequestMapping(value = "/saveCellConditions/{templateId}", method = RequestMethod.POST)
	public void saveCellConditions(@PathVariable String templateId, @RequestParam(value = "cellText") String cellText,
			@RequestParam(value = "row") String row, @RequestParam(value = "col") String col, Model model) {
		try {
			reportConditionService.deleteCellRowCol(templateId, row, col);
			List<RptTemplateCondition> rptTemplateConditionList = new ArrayList<RptTemplateCondition>();
			JsonResult jsonResult = new JsonResult();
			Map<String, String> map;
			map = jsonResult.jsonToString(cellText);
			Set<String> key = map.keySet();
			for (String strKey : key) {
				String strJson = "{" + map.get(strKey) + "}";
				JSONObject jobj = new JSONObject(strJson);
				RptTemplateCondition rptTemplateCondition = new RptTemplateCondition();
				rptTemplateCondition.setSetId(jobj.getString("cellXinxijiId"));
				rptTemplateCondition.setItemId(jobj.getString("cellXinxixiangId"));
				rptTemplateCondition.setConditionVal(jobj.getString("cellValue"));
				//这一定要注意，不是写错了，是前台写错了，不好改
				//逻辑运算服和关系运算服互相调换下位置，因为改页面太麻烦了，故在塞值的时候将其调换位置
				//逻辑连接符塞值
				rptTemplateCondition.setLogicOperator(jobj.getString("cellLianjieId"));
				//关系预算符塞值
				rptTemplateCondition.setRelaOperator(jobj.getString("cellLuojiyusuanfuId"));
				rptTemplateCondition.setConditionType(ConditionType.cell.getKey());
				rptTemplateCondition.setComboType(jobj.getString("cellShifouyouxianId"));
				rptTemplateCondition.setAbsRowNum(jobj.getString("hangNum"));
				rptTemplateCondition.setAbsColNum(jobj.getString("lieNum"));
				rptTemplateCondition.setTemplateId(templateId);
				rptTemplateCondition.setOrderId(Integer.parseInt(jobj.getString("orderId")));
				rptTemplateConditionList.add(rptTemplateCondition);
			}
			reportConditionService.insertList(rptTemplateConditionList);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//关系操作符转换
	public String getRelaOperatorName(String relaOperator) {
		switch (relaOperator) {
		case "1":
			return "等于";
		case "2":
			return "大于等于";
		case "3":
			return "小于等于";
		case "4":
			return "大于";
		case "5":
			return "小于";
		case "6":
			return "不等于";
		case "7":
			return "包含";
		case "8":
			return "按左侧匹配";
		case "9":
			return "按右侧匹配";
		default:
			return "";
		}
	}

	//是否优先转化
	public String getComboTypeName(String comboType) {
		switch (comboType) {
		case "1":
			return "左括号";
		case "2":
			return "右括号";
		default:
			return "";
		}
	}

	//逻辑运算符转换
	public String getLogicOperatorName(String logicOperator) {
		switch (logicOperator) {
		case "1":
			return "并且";
		case "2":
			return "或者";
		default:
			return "";
		}
	}

	//****************报表条件总控、行、列保存，修改方法*************************
	@RequestMapping("/preZongKongCreate/{templateId}")
	public String preZongKongCreate(@PathVariable String templateId, Model model) {
		model.addAttribute("templateId", templateId);
		return "report-design/report-template-conditions-zk-input";
	}

	@RequestMapping("/preHangCreate/{templateId}")
	public String preHangCreate(@PathVariable String templateId, Model model) {
		model.addAttribute("templateId", templateId);
		return "report-design/report-template-conditions-hang-input";
	}

	@RequestMapping("/preLieCreate/{templateId}")
	public String preLieCreate(@PathVariable String templateId, Model model) {
		model.addAttribute("templateId", templateId);
		return "report-design/report-template-conditions-lie-input";
	}

	@RequestMapping("/preConditionUpdate/{conditionId}/{templateId}/{type}")
	public String preZongKongUpdate(@PathVariable String conditionId, @PathVariable String templateId,
			@PathVariable String type, Model model) {
		RptTemplateCondition rptTemplateCondition = reportConditionService.getARptTemplateCondition(conditionId);
		//如果是列的话，需要做一步转换
		if (type.equals("3")) {
			rptTemplateCondition.setColLetter(CommonUtil.numToLetter(rptTemplateCondition.getRelColNum()));
		}
		model.addAttribute("rptTemplateCondition", rptTemplateCondition);
		model.addAttribute("templateId", templateId);
		if (type.equals("1")) {
			return "report-design/report-template-conditions-zk-input";
		} else if (type.equals("2")) {
			return "report-design/report-template-conditions-hang-input";
		} else if (type.equals("3")) {
			return "report-design/report-template-conditions-lie-input";
		} else {
			return "";
		}

	}

	@RequestMapping(value = "/saveZongKong", method = RequestMethod.POST)
	public String saveZongKong(RptTemplateCondition rptTemplateCondition, Model model) {
		rptTemplateCondition.setConditionType("1");
		reportConditionService.insert(rptTemplateCondition);
		model.addAttribute("message", "操作成功");
		return "report-design/report-template-conditions-zk-input";
	}

	@RequestMapping(value = "/saveHang", method = RequestMethod.POST)
	public String saveHang(RptTemplateCondition rptTemplateCondition, Model model) {
		rptTemplateCondition.setConditionType("2");
		reportConditionService.insert(rptTemplateCondition);
		model.addAttribute("message", "操作成功");
		return "report-design/report-template-conditions-hang-input";
	}

	@RequestMapping(value = "/saveLie", method = RequestMethod.POST)
	public String saveLie(RptTemplateCondition rptTemplateCondition, Model model) {
		rptTemplateCondition.setConditionType("3");
		rptTemplateCondition.setRelColNum(CommonUtil.letterToNum(rptTemplateCondition.getColLetter()));
		reportConditionService.insert(rptTemplateCondition);
		model.addAttribute("message", "操作成功");
		return "report-design/report-template-conditions-hang-input";
	}

	@RequestMapping(value = "/updateCondition", method = RequestMethod.POST)
	public String updateCondition(RptTemplateCondition rptTemplateCondition, Model model) {
		//如果是列的话，需要做一步转换
		if (rptTemplateCondition.getConditionType().equals("3")) {
			rptTemplateCondition.setRelColNum(CommonUtil.letterToNum(rptTemplateCondition.getColLetter()));
		}
		reportConditionService.update(rptTemplateCondition);
		model.addAttribute("message", "操作成功");
		if (rptTemplateCondition.getConditionType().equals("1")) {
			return "report-design/report-template-conditions-zk-input";
		} else if (rptTemplateCondition.getConditionType().equals("2")) {
			return "report-design/report-template-conditions-hang-input";
		} else if (rptTemplateCondition.getConditionType().equals("3")) {
			return "report-design/report-template-conditions-lie-input";
		} else {
			return "";
		}
	}

	@ResponseBody
	@RequestMapping(value = "/deleteTemplateConditionById/{conditionId}", method = RequestMethod.POST)
	public String deleteTemplateConditionById(@PathVariable String conditionId) {
		try {
			reportConditionService.delete(conditionId);
			return "success";
		} catch (Exception e) {
			return "false";
		}

	}
}
